package com.roamer.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Bean工具类
 *
 * @author roamer
 * @version V1.0
 * @date 2019/8/26 12:01 上午
 */
public abstract class BeanUtils {

    /**
     * 获取Class所有Field，包括其父类的Field
     *
     * @param clazz {@link Class}
     *
     * @return {@code List<Field>}
     */
    public static List<Field> getAllFieldsWithRoot(Class<?> clazz) {
        List<Field> fieldList = new ArrayList<>();
        //获取本类所有字段
        Field[] dFields = clazz.getDeclaredFields();
        if (dFields.length > 0) {
            fieldList.addAll(Arrays.asList(dFields));
        }

        // 若父类是Object，则直接返回当前Field列表
        Class<?> superClass = clazz.getSuperclass();
        if (superClass == Object.class) {
            return Arrays.asList(dFields);
        }

        // 递归查询父类的field列表
        List<Field> superFields = getAllFieldsWithRoot(superClass);
        if (!superFields.isEmpty()) {
            // 不重复字段
            superFields.stream().
                    filter(field -> !fieldList.contains(field)).
                               forEach(fieldList::add);
        }
        return fieldList;
    }
}
